package com.nxy.cpfsfe.busi.bolag;

import java.util.Date;
import java.util.Map;

import com.nxy.cpfsfe.mybatis.mapper.TbMnyAprtAMapper;
import com.nxy.cpfsfe.mybatis.pojo.TbMnyAprtA;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.nxy.cpfsfe.enumtype.MsgCdOrTpEnum;
import com.nxy.cpfsfe.enumtype.RespCd;
import com.nxy.cpfsfe.enumtype.RpcOutputInfoEnum;
import com.nxy.cpfsfe.enumtype.StatEnum;
import com.nxy.cpfsfe.enumtype.SysEcodeEnum;
import com.nxy.cpfsfe.enumtype.TAbEnum;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.util.DateUtil;
import com.nxy.cpfsfe.util.RpcCommUtil;
import com.nxy.cpfsfe.util.XmlUtil;

public class NCSMnyAprtSrvBean implements CpfsService {
	/**
	 * Description: 资金划拨申请
	 * @author  wp
	 * @date 2019年9月26日
	 * 
	 */
	private final static Logger LOGGER = LoggerFactory.getLogger(NCSMnyAprtSrvBean.class);
	SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");	
	
    public void doService() {		
		String bizMsg=null;
		try {
			String tpId = DtaInfo.getInstance().getTpId();		
			// 获取输入
			CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口	
			bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
			LOGGER.info("接收到输入BizMsg报文数据：" + bizMsg);
			String sndAppCd = (String) EPOper.get(tpId, "ReqBean[0].head[0].sndAppCd");
			regAgSeqProc(bizMsg,sndAppCd);
		} catch (Exception e) {
			LOGGER.error("NCS汇兑来账服务处理失败,原报文信息是："+bizMsg,e);
			throw new BaseException(RespCd.NCPO6047,e,"资金调拨申请");
		}		
	}
    
    //登记资金调拨流水
    public void regAgSeqProc(String bizMsg,String sndAppCd) {		
		//解包生成业务map
		Map<String, Object> map=null;
		try {
		    map = xml2BizMap(bizMsg,sndAppCd);		    
		    String chlSeqNo = (String) map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId");
		    String acqOrgId = (String) map.get("acqOrgId");
		    //String cpfsSeqNo = (String) map.get("cpfsSeqNo");
		    String xDirn = (String) map.get("xDirn");
		    String pCId = (String) map.get("pCId");
		    String sndOrgId = (String) map.get("/transaction/header/msg/sndMbrCd");
			TbMnyAprtA tbMnyAprtA = new TbMnyAprtA();
		    //tbA.setChlSeqNo(cpfsSeqNo);
			tbMnyAprtA.setAcqOrgId(acqOrgId);
			tbMnyAprtA.setxDirn(xDirn);
			tbMnyAprtA.setpCId(pCId);
			tbMnyAprtA.setSndOrgId(sndOrgId);
			tbMnyAprtA.setChlSeqNo(chlSeqNo);
			TbMnyAprtAMapper tbMnyAMapper = sqlSession.getMapper(TbMnyAprtAMapper.class);

			TbMnyAprtA tbMnyAObj = tbMnyAMapper.query(tbMnyAprtA);
		    if(tbMnyAObj == null){
		    	try{
					//插入数据账务流水表TbA	
					int tbAMappertResult = 0;
					tbAMappertResult = tbMnyAMapper.insertMnyAByMap(map);
					LOGGER.debug("资金调拨表TbMnyAprtA插入数据：[{}]条,报文标识号MsgId={}",tbAMappertResult,map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"));
					returnNPS365(bizMsg);
				}catch (Exception e) {
					LOGGER.warn("插入数据失败：资金调拨表TbMnyAprtA:"+map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"),e);
					throw new BaseException(RespCd.NCPS5002,e);
				}
		    }else{
		    	LOGGER.debug("账务流水表已存在该笔交易，转发该报文");
		    	returnNPS365(bizMsg);
		    }
			
		} catch (Throwable e) {
			LOGGER.error("BizMsg报文解包失败",e);
			throw new BaseException(RespCd.NCPO0101, e, "报文解析错误");
		}
				
	}
    
   //NPS.365转发给网关
  	public void returnNPS365(String bizMsg){
  		String tpId = DtaInfo.getInstance().getTpId();
  		try{
  			EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.NCS.getCode());
  	    	EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.MSGCD_365.getCode());
  		    EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", bizMsg);
  			RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	
  		}catch(Exception e){
  	    	LOGGER.error("调用网关转发NPS.365报文服务失败",e);
  			throw new BaseException(RespCd.NCPO6047,e,"调用网关服务异常");			
  		}
  		
  	}
  	
  	public Map<String, Object> xml2BizMap (String bizMsg,String sndAppCd){
  		
		Map<String, Object> map =null;
		try{
			//拆解xml报文为map1
			Map xml2BizMap = XmlUtil.xml2Map(bizMsg);
			//把map1<String, String>转换成map<String, Object>
			map = xml2BizMap;
            //String sndAppCd = (String) map.get("/transaction/header/msg/sndAppCd");
			map.put("drcrFlg", "2");
			//借贷记报文的TxId格式不一样
			map.put("cpfsSeqNo",StringUtils.isNotEmpty((String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"))?(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"):(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"));
			map.put("xSeqNo",StringUtils.isNotEmpty((String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"))?(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"):(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"));
			map.put("chlSeqNo",StringUtils.isNotEmpty((String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"))?(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"):(String)map.get("/transaction/body/FincgRqrmntNtfctn/GrpHdr/MsgId"));
			map.put("pNo", "1");
			map.put("chkASta", StatEnum.CHKASTA_NOT_START.getCode());   //未对账
			map.put("feAmt", "0.00"); //费率为0
			map.put("cpfsD", DateUtil.getSystemDate());
			map.put("xDirn", TAbEnum.XDirn_In.getCode());//12前置到通道
			map.put("bizSta",StatEnum.BIZSTA_ING.getCode());//往账进来刚开始都是：02处理中
			map.put("pCId",SysEcodeEnum.NCS.getCode());//NCS
			map.put("curTyp","CNY");
			map.put("bizSysId",sndAppCd);
			map.put("sndSysId",sndAppCd);
			map.put("rcvSysId",SysEcodeEnum.NCS.getCode());//NCS
			map.put("shardingId",map.get("/transaction/header/msg/sndMbrCd"));
			map.put("acqOrgId",map.get("/transaction/header/msg/sndMbrCd"));			
			map.put("chkASta",StatEnum.CHKASTA_NOT_START.getCode());//未对账
			map.put("creTm",DateUtil.getTimestamp(new Date()));
			LOGGER.info("资金调拨插入表参数map为：[{}]" , map.toString());
		}catch (Throwable e){
			throw new BaseException(RespCd.NCPO0101,e,"资金调拨申请报文解包异常");
		}
		return map;
  			
    }
	
}
